#!/usr/bin/env python3
"""
生产环境启动脚本 - 用于 spot.gitagent.io
启动后端服务在8001端口，前端服务在3001端口
"""

import subprocess
import sys
import os
import signal
import time
import logging
from datetime import datetime
from pathlib import Path

# 配置
BACKEND_PORT = 8001
FRONTEND_PORT = 3001
BACKEND_HOST = "0.0.0.0"
FRONTEND_HOST = "0.0.0.0"
LOGS_DIR = Path("logs")

def setup_logging():
    """设置日志配置"""
    LOGS_DIR.mkdir(exist_ok=True)
    
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(LOGS_DIR / "production.log", encoding='utf-8'),
            logging.StreamHandler(sys.stdout)
        ]
    )
    return logging.getLogger(__name__)

def kill_process_on_port(port):
    """杀死占用指定端口的进程"""
    try:
        result = subprocess.run(
            ['lsof', '-ti', f':{port}'],
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0 and result.stdout.strip():
            pids = result.stdout.strip().split('\n')
            for pid in pids:
                if pid:
                    try:
                        subprocess.run(['kill', '-9', pid], check=True)
                        print(f"✓ 已终止占用端口 {port} 的进程 (PID: {pid})")
                    except subprocess.CalledProcessError:
                        pass
        else:
            print(f"✓ 端口 {port} 未被占用")
            
    except Exception as e:
        print(f"⚠️ 检查端口 {port} 时出错: {e}")

def start_backend():
    """启动后端服务"""
    print(f"🚀 启动后端服务 (端口 {BACKEND_PORT})...")
    
    # 检查并清理端口
    kill_process_on_port(BACKEND_PORT)
    
    # 切换到backend目录
    backend_dir = Path("backend")
    if not backend_dir.exists():
        print("❌ backend目录不存在")
        return None
    
    # 启动后端
    cmd = [
        sys.executable, '-m', 'uvicorn', 
        'main:app',
        '--host', BACKEND_HOST,
        '--port', str(BACKEND_PORT),
        '--workers', '4',  # 生产环境使用多个worker
        '--log-level', 'info'
    ]
    
    try:
        process = subprocess.Popen(
            cmd,
            cwd=backend_dir,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )
        
        print(f"✓ 后端服务已启动 (PID: {process.pid})")
        print(f"✓ 服务地址: http://{BACKEND_HOST}:{BACKEND_PORT}")
        
        return process
        
    except Exception as e:
        print(f"❌ 启动后端服务失败: {e}")
        return None

def start_frontend():
    """启动前端服务"""
    print(f"🌐 启动前端服务 (端口 {FRONTEND_PORT})...")
    
    # 检查并清理端口
    kill_process_on_port(FRONTEND_PORT)
    
    # 启动前端 (使用Python简单HTTP服务器)
    cmd = [
        sys.executable, '-m', 'http.server', 
        str(FRONTEND_PORT),
        '--bind', FRONTEND_HOST
    ]
    
    try:
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )
        
        print(f"✓ 前端服务已启动 (PID: {process.pid})")
        print(f"✓ 服务地址: http://{FRONTEND_HOST}:{FRONTEND_PORT}")
        
        return process
        
    except Exception as e:
        print(f"❌ 启动前端服务失败: {e}")
        return None

def main():
    """主函数"""
    logger = setup_logging()
    
    print("🌟 spot.gitagent.io - 生产环境启动")
    print("=" * 60)
    
    # 启动后端服务
    backend_process = start_backend()
    if not backend_process:
        print("❌ 后端服务启动失败，退出")
        sys.exit(1)
    
    # 等待后端启动
    time.sleep(3)
    
    # 启动前端服务
    frontend_process = start_frontend()
    if not frontend_process:
        print("❌ 前端服务启动失败，但后端已启动")
    
    print("-" * 60)
    print("🎉 服务启动完成!")
    print(f"📱 前端地址: http://localhost:{FRONTEND_PORT}")
    print(f"🔧 后端API: http://localhost:{BACKEND_PORT}")
    print("🌐 生产地址: https://spot.gitagent.io")
    print("按 Ctrl+C 停止所有服务")
    print("-" * 60)
    
    # 等待中断信号
    try:
        while True:
            time.sleep(1)
            
            # 检查进程是否还在运行
            if backend_process and backend_process.poll() is not None:
                print("⚠️ 后端服务意外停止")
                break
                
            if frontend_process and frontend_process.poll() is not None:
                print("⚠️ 前端服务意外停止")
                
    except KeyboardInterrupt:
        print("\n🛑 收到停止信号，正在关闭服务...")
        
        # 停止服务
        if backend_process:
            backend_process.terminate()
            backend_process.wait()
            print("✓ 后端服务已停止")
            
        if frontend_process:
            frontend_process.terminate()
            frontend_process.wait()
            print("✓ 前端服务已停止")
        
        print("👋 所有服务已停止")

if __name__ == "__main__":
    main()
